package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 用户发送短信类
 */
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService us;

    /**
     * 登入
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map<String, String> map, HttpSession session) {
        String phone = map.get("phone");
        String code = map.get("code");
        String valCode = (String) session.getAttribute(phone);
        //拿着手机号取看看这个用户在不在数据库
        if (valCode.equalsIgnoreCase(code)) {
            User user = us.findByPhone(phone);
            //如果根据手机号在数据库存在
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                us.add(user);
            }
            session.setAttribute("user", user);

            return R.success("登入成功!");
        }
        return R.error("登入失败！");
    }

    /**
     * 获取验证码
     *
     * @param phone
     * @param session
     * @return
     */
    @GetMapping("/smscode")
    public R sendSmsCode(String phone, HttpSession session) {
        //1.生成验证码
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        //2.给手机号放短信
        //3. 为了能够去校验一会登录传递上来的验证码是否正确，需要把这个验证码保存到session作用域
        session.setAttribute(phone, code);

        return R.success(code);
    }

    /**
     * 退出登入
     * @param session
     * @return
     */
    @GetMapping("/logout")
    public R logout(HttpSession session) {
        //退出登入销毁 session存储的值
        session.invalidate();
        return R.success("退出登入成功");
    }
}
